<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <!-- <lb-layout
      v-loading="$store.getters.loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="#a19f9fb0;"
    > -->

    <Title name="3D位置信息" :line="false">
      <el-row>
        <el-col :offset="6" :span="16">
          <aps-form
            :config="apsForm.formConfig"
            :model="apsForm.formData"
            :formRef="apsForm.formRef"
            :labelWidth="apsForm.labelWidth"
            ref="form"
          ></aps-form>
        </el-col>
      </el-row>
    </Title>

    <Title name="绑定设备信息" :line="false" class="mt20">
      <el-row>
        <el-col :span="24">
          <aps-form
            :config="searchapsForm.formConfig"
            :model="searchapsForm.formData"
            :formRef="searchapsForm.formRef"
            :labelWidth="searchapsForm.labelWidth"
            ref="searchform"
          ></aps-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <lb-table
            border
            height="370"
            :column="tableData.column"
            :data="tableData.data"
            background
            layout="total, sizes, prev, pager, next, jumper"
            class="addCourseTypeTable"
          >
            <!-- pagination
              :page-sizes="[5, 10, 20, 30]"
              :pager-count="5"
              :current-page.sync="currentPage"
              :total="total"
              :page-size="pageSize"
              @size-change="handleSizeChange"
              @p-current-change="handleCurrentChange" -->
            <!-- @selection-change="handleSelectionChange" -->
          </lb-table>
        </el-col>
      </el-row>
    </Title>

    <addPop
      :visible.sync="visible"
      :filtrateParams="filtrateParams"
      :locationParams="locationParams"
      @popClose="popClose"
    ></addPop>
    <!-- </lb-layout> -->
  </lb-layout>
</template>

<script>
import addPop from "@/views/configuration/basicdata/location/components/add.vue";
import { deepClone } from "@/utils/index";
import {
  getParkList,
  getBuildingList,
  getFacilitiesList,
  getRoomList,
} from "@/api/system/dept.js";
import {
  get3Dlist,
  getEquipmentlist,
  putEquipment,
} from "@/api/basicdata/location.js";

export default {
  components: {
    addPop,
  },
  dicts: [
    "device_type", // 设备类型
    "model_location", // 模型3d位置类型
  ],
  data() {
    return {
      visible: false,
      // 新增查询限制条件
      filtrateParams: {},
      // 选择的3D位置的名称和ID信息
      locationParams: {
        name: "3D位置名称",
        id: null,
      },
      parkArr: [], // 园区集合
      buildingArr: [], // 楼幢集合
      facilitiesArr: [], // 楼层集合
      roomArr: [], // 房间集合
      architectureModelIdArr: [], // 3d位置
      apsForm: {
        formRef: "form",
        labelWidth: "100px",
        formData: {},
        formConfig: {
          formAttr: {
            size: "small",
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 2,
              middle: true,
            },
            rules: {
              parkId: [
                {
                  required: true,
                  message: "请选择园区位置",
                  trigger: ["change", "bulr"],
                },
              ],
              buildingId: [
                {
                  required: true,
                  message: "请选择楼幢编号",
                  trigger: ["change", "bulr"],
                },
              ],
              facilitiesId: [
                {
                  required: true,
                  message: "请选择楼层编号",
                  trigger: ["change", "bulr"],
                },
              ],
            },
          },
          properties: {
            parkId: {
              label: "园区位置",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = that.parkArr;
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择园区位置",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.$forceUpdate();
                          that.$refs?.form?.setFieldValue(
                            "buildingId",
                            undefined
                          );
                          that.$refs?.form?.setFieldValue(
                            "facilitiesId",
                            undefined
                          );
                          that.$refs?.form?.setFieldValue("roomId", undefined);
                          that.$refs?.form?.setFieldValue(
                            "architectureModelId",
                            undefined
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildingId: {
              label: "楼幢编号",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = that.buildingArr;
                let valNum = that.$refs?.form?.getFieldsValue().buildingId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼幢编号",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        "visible-change": ($event) => {
                          // 下拉打开时$event为true，关闭时为false
                          that.handleGetBuildingList($event);
                        },
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildingId", value);
                          that.$forceUpdate();
                          that.$refs?.form?.setFieldValue(
                            "facilitiesId",
                            undefined
                          );
                          that.$refs?.form?.setFieldValue("roomId", undefined);
                          that.$refs?.form?.setFieldValue(
                            "architectureModelId",
                            undefined
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            facilitiesId: {
              label: "楼层编号",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = that.facilitiesArr;
                let valNum = that.$refs?.form?.getFieldsValue().facilitiesId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼层编号",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        "visible-change": ($event) => {
                          that.handleGetFacilitiesList($event);
                        },
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "facilitiesId",
                            value
                          );
                          that.$forceUpdate();
                          that.$refs?.form?.setFieldValue("roomId", undefined);
                          that.$refs?.form?.setFieldValue(
                            "architectureModelId",
                            undefined
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            roomId: {
              label: "房间号",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = that.roomArr;
                let valNum = that.$refs?.form?.getFieldsValue().roomId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择房间号",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        "visible-change": ($event) => {
                          that.handleGetRoomList($event);
                        },
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("roomId", value);
                          that.$refs?.form?.setFieldValue(
                            "architectureModelId",
                            undefined
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            type: {
              label: "3D位置类型",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.model_location.some((item) => {
                  arr.push(item);
                });
                let valNum = that.$refs?.form?.getFieldsValue().type;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择3D位置类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("type", value);
                          that.$forceUpdate();
                          that.$refs?.form?.setFieldValue(
                            "architectureModelId",
                            undefined
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            architectureModelId: {
              label: "3D位置信息",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = that.architectureModelIdArr;
                let valNum =
                  that.$refs?.form?.getFieldsValue().architectureModelId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择3D位置信息",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        "visible-change": () => {
                          that.$refs.form.validate((valid) => {
                            if (valid) {
                              that.handleget3Dlist();
                            }
                          });
                        },
                        change: (val) => {
                          that.locationParams.id = val;
                          that.architectureModelIdArr.map((item) => {
                            if (item.value == val) {
                              that.locationParams.name = item.label;
                            }
                          });
                          that.$refs?.form?.setFieldValue(
                            "architectureModelId",
                            val
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchlocation,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            // {
            //   label: "智能设备档案",
            //   type: "primary",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-right",
            //   click: this.handlerGoarchives,
            // },
            // {
            //   label: "保存",
            //   type: "success",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-finished",
            //   click: this.handleSubmit,
            // },
          ],
        },
      },
      searchapsForm: {
        formRef: "searchform",
        labelWidth: "100px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            type: {
              label: "设备类型:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.device_type.some((item) => {
                  arr.push(item);
                });
                let valNum = that.$refs?.searchform?.getFieldsValue().type;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.searchform?.setFieldValue("type", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            code: {
              label: "设备编号:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入设备编号",
            },
            cardNum: {
              label: "物联网卡号:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入物联网卡号",
            },
          },
          formSoltButton: [
            // {
            //   label: "筛选",
            //   type: "primary",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-search",
            //   click: this.handlerSearchTable,
            // },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-plus",
              click: this.handleAdd,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleResetTable,
            },
          ],
        },
      },
      tableData: {
        column: [
          // {
          //   type: "selection",
          // },
          {
            prop: "name",
            label: "设备名称",
            showOverflowTooltip: true,
          },
          {
            prop: "code",
            label: "设备编号",
            showOverflowTooltip: true,
          },
          {
            prop: "type",
            label: "设备类型",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.device_type}
                    value={scope.row.type}
                  />
                </div>
              );
            },
          },
          // {
          //   prop: "cardNum",
          //   label: "物联网卡号",
          //   showOverflowTooltip: true,
          // },
          {
            label: "操作",
            width: "300",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let c;
              let inlineStyle = {
                display: "flex",
              };
              c = (
                <el-button
                  type="text"
                  size="small"
                  class="text-danger"
                  icon="el-icon-delete"
                  onClick={() => {
                    this.handleOperDelete(scope.row);
                  }}
                >
                  解绑
                </el-button>
              );
              return <div style={inlineStyle}>{c}</div>;
            },
          },
        ],
        data: [],
      },
      // currentPage: 1,
      // pageSize: 10,
      // total: 0,
    };
  },
  created() {},
  mounted() {
    this.handleGetParkList();
  },
  methods: {
    handlerGoarchives() {
      this.$router.push({ path: "/iot/archives" });
    },
    // 获取园区集合
    handleGetParkList() {
      this.parkArr = [];
      getParkList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, "园区");
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                value: item.id,
                label: item.name,
              };
              this.parkArr.push(obj);
            });
          }
        })
        .catch(() => {});
    },
    // 获取楼幢集合
    handleGetBuildingList(e) {
      this.buildingArr = [];
      let params = this.$refs?.form?.getFieldsValue().parkId;
      if (params == "" || params == undefined || params == null) {
        if (e) {
          this.$message.warning("请先选择园区");
        }
        return false;
      }
      if (e) {
        getBuildingList(params)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            // console.log(res, "楼幢");
            let arr = res?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                let obj = {
                  value: item.id,
                  label: item.name,
                };
                this.buildingArr.push(obj);
              });
            } else {
              this.$message.warning("请该园区下楼幢不存在");
            }
          })
          .catch(() => {});
      }
    },
    // 获取楼层集合
    handleGetFacilitiesList(e) {
      this.facilitiesArr = [];
      let params = this.$refs?.form?.getFieldsValue().buildingId;
      if (params == "" || params == undefined || params == null) {
        if (e) {
          this.$message.warning("请先选择楼幢");
        }
        return false;
      }
      if (e) {
        getFacilitiesList(params)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            // console.log(res, "楼层");
            let arr = res?.rows ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                let obj = {
                  value: item.id,
                  label: item.name,
                };
                this.facilitiesArr.push(obj);
              });
            } else {
              this.$message.warning("该楼幢下楼层不存在");
            }
          })
          .catch(() => {});
      }
    },
    // 获取房间集合
    handleGetRoomList(e) {
      this.roomArr = [];
      let params = this.$refs?.form?.getFieldsValue().facilitiesId;
      if (params == "" || params == undefined || params == null) {
        if (e) {
          this.$message.warning("请先选择楼层");
        }
        return false;
      }
      if (e) {
        getRoomList(params)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            // console.log(res, "房间");
            let arr = res?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                let obj = {
                  value: item.id,
                  label:
                    item.remarks + item.roomStartNum + "——" + item.roomEndNum,
                };
                this.roomArr.push(obj);
              });
            } else {
              this.$message.warning("该楼层下房间不存在");
            }
          })
          .catch(() => {});
      }
    },
    // 获取3D位置集合
    handleget3Dlist() {
      this.architectureModelIdArr = [];
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      let buildingId = this.$refs?.form?.getFieldsValue().buildingId;
      let facilitiesId = this.$refs?.form?.getFieldsValue().facilitiesId;
      let roomId = this.$refs?.form?.getFieldsValue().roomId;
      let type = this.$refs?.form?.getFieldsValue().type;
      let params = {
        parkId: parkId ? parkId : null,
        buildingId: buildingId ? buildingId : null,
        facilitiesId: facilitiesId ? facilitiesId : null,
        roomId: roomId ? roomId : null,
        type: type ? type : null,
      };
      get3Dlist(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, "3D位置集合");
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                value: item.id,
                label: item.meshName ? item.meshName : "3D位置名称",
              };
              this.architectureModelIdArr.push(obj);
            });
          } else {
            this.$message.warning("该物理位置下3D位置不存在");
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!200300");
        });
    },
    /* 搜索位置信息的设备列表 */
    handlerSearchlocation() {
      this.handlerSearchTable();
    },
    handleReset() {
      this.$refs?.form?.resetFields();
      this.$refs?.searchform?.resetFields();
      this.tableData.data = [];
      this.locationParams = {
        name: "3D位置名称",
        id: null,
      };
      this.architectureModelIdArr = [];
      this.handleGetParkList(); // 重新获取园区集合
    },
    // handleSubmit() {},
    /* 筛选设备列表 */
    handlerSearchTable() {
      let that = this;
      let architectureModelId =
        this.$refs?.form?.getFieldsValue().architectureModelId;
      if (
        !architectureModelId ||
        architectureModelId == undefined ||
        architectureModelId == null
      ) {
        that.$message({
          message: "请先选择3D位置信息",
          type: "warning",
        });
      } else {
        let query = {
          architectureModelId: architectureModelId,
          // ...this.$refs?.searchform?.getFieldsValue(),
        };
        // query.pageNum = that.currentPage;
        // query.pageSize = that.pageSize;
        console.log(query, "qqcs");
        that.$store.commit("app/updateApiCount", "add");
        getEquipmentlist(query)
          .then((res) => {
            that.$store.commit("app/updateApiCount");
            if (res.code === 700) {
              that.$message.warning(res.msg);
              return false;
            }
            that.tableData.data = res?.data ?? [];
            // that.total = res.total;
          })
          .catch(() => {
            that.$store.commit("app/updateApiCount");
            // this.$message.error("系统错误,请联系管理员!200301");
          });
      }
    },
    handleResetTable() {
      this.$refs?.searchform?.resetFields();
    },
    /* 新增设备 */
    handleAdd() {
      let type = this.$refs?.searchform?.getFieldsValue().type;
      let code = this.$refs?.searchform?.getFieldsValue().code;
      let cardNum = this.$refs?.searchform?.getFieldsValue().cardNum;
      // console.log(type, code, cardNum);
      if (this.locationParams.id == null) {
        this.$message({
          message: "请先确定选择3D位置信息搜索后再新增",
          type: "warning",
        });
        return false;
      }
      // if (!type && !code && !cardNum) {
      //   this.$message({
      //     message: "请先至少限制一条新增查询条件后再新增",
      //     type: "warning",
      //   });
      //   return false;
      // }
      this.filtrateParams = deepClone({
        type: type,
        code: code,
        cardNum: cardNum,
      });
      setTimeout(() => {
        this.visible = true;
      }, 200);
    },
    // handleSizeChange(val) {
    //   this.currentPage = 1;
    //   this.pageSize = val;
    //   this.handlerSearchTable();
    // },
    // handleCurrentChange(val) {
    //   this.currentPage = val;
    //   this.handlerSearchTable();
    // },
    /* 删除 */
    handleOperDelete(row) {
      let that = this;
      that.$modal
        .confirm("是否确定解绑此数据项？")
        .then(() => {
          let params = {
            architectureModelId: null,
            id: row?.id,
          };
          putEquipment(params)
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.$message({
                message: "解绑成功",
                type: "success",
              });
              setTimeout(() => {
                that.handlerSearchTable();
              }, 200);
            })
            .catch(() => {
              // this.$message.error("系统错误,请联系管理员!200302");
            });
        })
        .catch(() => {
          that.$message("取消解绑");
        });
    },
    popClose(flag) {
      if (flag) {
        // 新增成功刷新列表
        this.handlerSearchTable();
      }
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
.scoller-y {
  // max-height: 400px;
  margin-top: 10px;
  // overflow-y: auto;
  @include scrollBar2;
}
::v-deep .el-table__body-wrapper {
  @include scrollBar2;
}
</style>
